Props in ReactJS

react-js-props

React allows us to send information to a Component using something named props. Props are basically a kind of global variable or object. In this post, we will read about this in more detail.

When React sees an element representing a user-defined component, it passes JSX attributes to this component as a single object. We call this object “props”.

We can pass props to any component as we assign attributes to any HTML tag. Take a quick look at the below code snippet:

For Example:

In the above code snippet, we are passing a prop named ‘name’, ’empid’ to the component named “Employee”. This prop has a value “Pradeep”, “101”. Let us now see how can we access these props.

Below is an example program to show how to pass and access props from a component:

Props in Function-Based Component:

Output:

React-App
In the example above, we used a function-based component to explain props, but we can also pass props to a class-based component just as we did in the example above, but we need to use the ‘ this ‘ keyword to obtain the prop from a function.

Props in Class-Based Component:

The output of this program will be the same as that of the above program.

Note:-

  1. If you pass no value for a prop, it default to true.
  2. Whether you declare a component as a function or class, it must never modify its own props.
  3. All React components must act like pure function with respect to their props.

Passing information from Parent component to Child Component

We’re going to view two components Parent and Children to make this clear. We will pass some information from our parent component to the child component as props. We can pass as many props as we want on a component.

For Example:

Output :-

So we’ve seen React props, and we’ve also found how to use props, how to pass them on to a component, how to access them inside a component, and much more. We used the “this.props.propName” portion very often to receive props in these details of the situation.

What is JSX in React?

Reference:
https://reactjs.org/docs/components-and-props.html

Related posts